package com.example.usermanagement.service;

import com.example.usermanagement.dto.UserDTO;
import com.example.usermanagement.entity.User;
import com.example.usermanagement.entity.UserLog;
import com.example.usermanagement.mapper.UserLogMapper;
import com.example.usermanagement.mapper.UserMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    private final UserMapper userMapper;
    private final UserLogMapper userLogMapper;
    private final PasswordEncoder passwordEncoder;
    private final RedisTemplate<String, Object> redisTemplate;

    public UserService(UserMapper userMapper, UserLogMapper userLogMapper,
                       PasswordEncoder passwordEncoder, RedisTemplate<String, Object> redisTemplate) {
        this.userMapper = userMapper;
        this.userLogMapper = userLogMapper;
        this.passwordEncoder = passwordEncoder;
        this.redisTemplate = redisTemplate;
    }

    public User registerUser(UserDTO userDTO) {
        if (userMapper.findByUsername(userDTO.getUsername()).isPresent()) {
            throw new IllegalArgumentException("用户名已存在");
        }
        if (userMapper.findByEmail(userDTO.getEmail()).isPresent()) {
            throw new IllegalArgumentException("邮箱已存在");
        }

        User user = new User();
        user.setUsername(userDTO.getUsername());
        user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
        user.setEmail(userDTO.getEmail());
        user.setRole(userDTO.getRole() != null ? userDTO.getRole() : "USER");
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        userMapper.insert(user);

        UserLog log = new UserLog();
        log.setUserId(user.getId());
        log.setAction("REGISTER");
        log.setTimestamp(LocalDateTime.now());
        userLogMapper.insert(log);

        redisTemplate.opsForValue().set("user:" + user.getUsername(), user, 1, TimeUnit.HOURS);

        return user;
    }

    public List<User> getAllUsers() {
        return userMapper.findAll();
    }

    public List<UserLog> getUserLogs() {
        return userLogMapper.findAll(); // 调用新增的 findAll 方法
    }

    public User getCurrentUser() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        return (User) redisTemplate.opsForValue().get("user:" + username);
    }
}